package com.cdh.search.controller;



import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cdh.search.client.ElasticsearchConfig;
import com.cdh.search.domain.po.Item;
import com.cdh.search.domain.po.ItemDoc;
import com.cdh.search.domain.query.ItemPageQuery;
import com.cdh.search.service.IItemService;
import com.heima.dto.ItemDTO;
import com.hmall.common.domain.PageDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Api(tags = "搜索相关接口")
@RestController
@RequestMapping("/search")
@RequiredArgsConstructor
public class SearchController {

    private final ElasticsearchConfig elasticsearchConfig;

    private final IItemService itemService;

    /*@ApiOperation("搜索商品")
    @GetMapping("/list")
    public PageDTO<ItemDTO> search(ItemPageQuery query) {
        // 分页查询
        Page<Item> result = itemService.lambdaQuery()
                .like(StrUtil.isNotBlank(query.getKey()), Item::getName, query.getKey())
                .eq(StrUtil.isNotBlank(query.getBrand()), Item::getBrand, query.getBrand())
                .eq(StrUtil.isNotBlank(query.getCategory()), Item::getCategory, query.getCategory())
                .eq(Item::getStatus, 1)
                .between(query.getMaxPrice() != null, Item::getPrice, query.getMinPrice(), query.getMaxPrice())
                .page(query.toMpPage("update_time", false));
        // 封装并返回
        return PageDTO.of(result, ItemDTO.class);
    }*/
    @ApiOperation("搜索商品")
    @GetMapping("/list")
    public PageDTO<ItemDTO> search(ItemPageQuery query) throws IOException {
        // 搜索
        // 1.准备Request对象
        SearchRequest request = new SearchRequest("items");
        // 2.组织DSL参数
        // 2.1.准备bool查询
        BoolQueryBuilder bool = QueryBuilders.boolQuery();
        if (StrUtil.isNotBlank(query.getKey())) {
            // 关键字搜索
            bool.must(QueryBuilders.matchQuery("name", query.getKey()));
        }
        if (StrUtil.isNotBlank(query.getCategory())) {
            // 分类过滤
            bool.filter(QueryBuilders.termQuery("category.keyword", query.getCategory()));
        }
        if (StrUtil.isNotBlank(query.getBrand())) {
            // 品牌过滤
            bool.filter(QueryBuilders.termQuery("brand.keyword", query.getBrand()));
        }
        if (query.getMaxPrice() != null) {
            // 价格最大值过滤
            bool.filter(QueryBuilders.rangeQuery("price").lte(query.getMaxPrice()));
        }
        if (query.getMinPrice() != null) {
            // 价格最小值过滤
            bool.filter(QueryBuilders.rangeQuery("price").gte(query.getMinPrice()));
        }
        request.source().query(bool);
        // 分页
        request.source().from((query.getPageNo() - 1) * query.getPageSize()).size(query.getPageSize());
        // 排序
        if (StrUtil.isNotBlank(query.getSortBy())) {
            request.source().sort(query.getSortBy(), query.getIsAsc()? SortOrder.ASC : SortOrder.DESC);
        } else {
            request.source().sort("updateTime", query.getIsAsc()? SortOrder.ASC : SortOrder.DESC);
        }
        // 3.发送请求
        SearchResponse response = elasticsearchConfig.elasticsearchClient().search(request, RequestOptions.DEFAULT);
        // 4.解析结果
        PageDTO<ItemDTO> itemDTOPageDTO = parseResponseResult(response, query);
        // client.close();
        return itemDTOPageDTO;
    }

    private PageDTO<ItemDTO> parseResponseResult(SearchResponse response, ItemPageQuery query) {
        // 1.0.创建一个集合
        List<ItemDoc> itemDocList = new ArrayList<>();

        SearchHits searchHits = response.getHits();
        // 1.1.总条数
        long total = searchHits.getTotalHits().value;

        // 1.2.命中的数据
        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {
            // 4.2.1.获取source结果
            String json = hit.getSourceAsString();
            // 4.2.2转为ItemDoc
            ItemDoc doc = JSONUtil.toBean(json, ItemDoc.class);
            // 封装到集合
            itemDocList.add(doc);
        }
        // 2.转为ItemDTO集合
        List<ItemDTO> itemDTOS = BeanUtil.copyToList(itemDocList, ItemDTO.class);
        // 2.1页面大小
        Long pageSize = query.getPageSize().longValue();
        // 2.2返回结果
        PageDTO<ItemDTO> itemDTOPageDTO = new PageDTO<>(total, pageSize, itemDTOS);
        return itemDTOPageDTO;
    }

    @ApiOperation("过滤商品栏")
    @PostMapping("/filters")
    public Map filters(@RequestBody ItemPageQuery query) throws IOException {
        //1.准备Request对象
        SearchRequest request = new SearchRequest("items");
        //2.组织DSL参数
        if (StrUtil.isNotBlank(query.getKey())) {
            // 关键字搜索
            request.source().query(QueryBuilders.matchQuery("name", query.getKey()));
        }
        //2.1.分页
        request.source().size(0);
        //2.2.聚合条件
        String brandAgg = "brand_agg";
        String categoryAgg = "category_agg";
        request.source().aggregation(AggregationBuilders.terms(brandAgg).field("brand.keyword").size(10));
        request.source().aggregation(AggregationBuilders.terms(categoryAgg).field("category.keyword").size(10));
        //3.发送请求
        SearchResponse response = elasticsearchConfig.elasticsearchClient().search(request, RequestOptions.DEFAULT);
        //4.解析结果
        Aggregations aggregations = response.getAggregations();
        //4.1根据聚合名称获取对应的聚合
        Terms brandAggTerms = aggregations.get(brandAgg);
        Terms categoryAggTerms = aggregations.get(categoryAgg);
        //4.2获取buckets
        List<? extends Terms.Bucket> brandBuckets = brandAggTerms.getBuckets();
        List<? extends Terms.Bucket> categoryBuckets = categoryAggTerms.getBuckets();
        //4.3遍历获取每一个bucket
        List<String> brandList = new ArrayList<>();
        List<String> categoryList = new ArrayList<>();
        Map<String, List<String>> map = new HashMap<>();
        for (Terms.Bucket brandBucket : brandBuckets) {
            brandList.add(brandBucket.getKeyAsString());
        }
        for (Terms.Bucket categoryBucket : categoryBuckets) {
            categoryList.add(categoryBucket.getKeyAsString());
        }
        map.put("brand", brandList);
        map.put("category", categoryList);
        // client.close();
        return map;
    }
}
